package com.yuexunit.mobilenurse.module.BloodManage.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.base.titlebar.TitleBar_DocAdvice;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.BloodManage.adapter.ApplyAdapter;
import com.yuexunit.mobilenurse.module.BloodManage.bean.BloodDataBean;
import com.yuexunit.mobilenurse.module.BloodManage.bean.SingleBloodBag;
import com.yuexunit.mobilenurse.module.BloodManage.model.impl.BloodApplyModel;
import com.yuexunit.mobilenurse.module.BloodManage.presenter.IBloodApplyPresenter;
import com.yuexunit.mobilenurse.module.BloodManage.presenter.impl.BloodApplyPresenter;
import com.yuexunit.mobilenurse.module.BloodManage.ui.view.IBloodApplyView;
import com.yuexunit.mobilenurse.util.CreateJson;
import com.yuexunit.mobilenurse.widget.EmptyLayout;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.SystemTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/3/21 0021.
 */

public class Act_Blood_Apply_Lachsis extends TitleBar_DocAdvice implements IBloodApplyView {
    @Bind(R.id.titlebar_docadvice_tv_title)
    public TextView titlebar_docadvice_tv_title;
    @Bind(R.id.docactvice_name)
    public TextView docactvice_name;
    @Bind(R.id.docactvice_bedno)
    public TextView docactvice_bedno;
    @Bind(R.id.docactvice_visitno)
    public TextView docactvice_visitno;
    @Bind(R.id.act_testdetail_list)
    public ListView act_testdetail_list;
    @Bind(R.id.empty_layout)
    public EmptyLayout mEmptyLayout;

    public static final int DOWNLOAD_NETERROR = -1;

    //记录Log
    private final Logger log = LoggerFactory.getLogger(Act_Blood_Apply_Joyree.class);

    BaseAdapter adapter;

    IBloodApplyPresenter presenter;

    private ValueBroadcastReceiver valueBroadcastReceiver = null;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_blood_apply);
        ButterKnife.bind(this);
        presenter = new BloodApplyPresenter(new BloodApplyModel(),this);
    }

    @Override
    public void initData() {
        super.initData();
        mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        startBarcodeBroadcastReceiver();
        if(SystemTool.checkNet(aty)) {
            Map<String, String> params = new HashMap<>();
//            params.put("visitNo","492746");
            params.put("visitNo", PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO));
            params.put("pageIndex","1");
            params.put("pageSize","9999");
            presenter.getBloodDataList(params);
        }
        else
        {
            ViewInject.toast("网络异常，请检查网络是否连接!");
            log.error(CreateJson.LOG_JSON("", "1", PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_DEPTNO), ""));
        }
    }

    @Override
    public void setTitle()
    {
        titlebar_docadvice_tv_title.setText("申请列表");
        docactvice_name.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME));
        docactvice_bedno.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE));
        docactvice_visitno.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO));
    }

    @Override
    public  void onBackClick()
    {
        finish();
    }




    @Override
    public void showBloodDataList(BloodDataBean bloodDataBean) {
        adapter = new ApplyAdapter(act_testdetail_list,bloodDataBean.getDatas(),R.layout.item_apply);
        act_testdetail_list.setAdapter(adapter);
        mEmptyLayout.dismiss();
    }

    @Override
    public void PullDownRefreshState(int state) {
        switch (state) {
            case DOWNLOAD_NETERROR:
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                break;
        }
    }

    @Override
    public void getBloodBagData(SingleBloodBag singleBloodBag) {
        if(singleBloodBag.getStatus().equals("200"))
        {
            Bundle bundle = new Bundle();
            bundle.putString("requireNo",singleBloodBag.getDatas().get(0).getRequireNo());
            bundle.putSerializable("bloodbag",singleBloodBag.getDatas().get(0));
            Intent intent = new Intent(aty,Act_Blood_BloodDetail.class);
            intent.putExtras(bundle);
            startActivity(intent);
        }
        else {
            ViewInject.toast(singleBloodBag.getMessage());
        }
    }

    @Override
    public void onStop(){
        super.onStop();
        stopBarcodeBroadcastReceiver();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        stopBarcodeBroadcastReceiver();
    }

    /**
     * 停止接收广播
     */
    private void stopBarcodeBroadcastReceiver() {
        try {
            if (valueBroadcastReceiver != null)
                unregisterReceiver(valueBroadcastReceiver);
        } catch (Exception e) {

        }
    }

    /**
     * 开始接收广播
     */
    private void startBarcodeBroadcastReceiver() {
        try {
            if (valueBroadcastReceiver == null)
                valueBroadcastReceiver = new ValueBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("lachesis_barcode_value_notice_broadcast");
            registerReceiver(valueBroadcastReceiver, filter);
        } catch (Exception e) {

        }
    }


    /**
     * 关机广播接收者
     *
     * @author
     *
     */
    private class ValueBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            Log.i("ValueBroadcastReceiver", "onReceive......");
            final String value = arg1
                    .getStringExtra("lachesis_barcode_value_notice_broadcast_data_string");
            if(!value.equals(""))
            {
                String code = "15"+value;
                if(code.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_YX_RULE)))
//                    if(code.length()==10)
                {
                    Map<String, String> params = new HashMap<>();
                    params.put("bagNo", code);
                    TelephonyManager telephonyManager = (TelephonyManager) aty
                            .getSystemService(Context.TELEPHONY_SERVICE);
                    params.put("setNo", telephonyManager.getDeviceId());
                    presenter.getBloodBagData(params);
                }
                else {
                    ViewInject.toast("此条码不是血袋号");
                }
            }
        }
    }
}
